package me.zhengjie.minbearwcs.serivce.mission.processor.inbound;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.minbearwcs.dao.storage.inf.SmallStorageDao;
import me.zhengjie.minbearwcs.entity.PO.wcs.inbound.status.InboundOrderDetailStatus;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionTemplate;
import me.zhengjie.minbearwcs.dao.inbound.inf.InboundOrderDetailDao;
import me.zhengjie.minbearwcs.dao.mission.inf.WcsMissionDao;
import me.zhengjie.minbearwcs.entity.DTO.agv.task.AgvActionSource;
import me.zhengjie.minbearwcs.entity.DTO.agv.task.AgvTaskSource;
import me.zhengjie.minbearwcs.entity.DTO.agv.task.actionEnum.AgvAction;
import me.zhengjie.minbearwcs.entity.DTO.transfer.Tuple;
import me.zhengjie.minbearwcs.entity.PO.agv.missionEnum.AgvMissionType;
import me.zhengjie.minbearwcs.entity.PO.wcs.inbound.InboundOrderDetail;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.WcsMission;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.status.InboundMissionFor3Or4FloorStatus;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.type.MissionType;
import me.zhengjie.minbearwcs.resource.WcsResource;
import me.zhengjie.minbearwcs.serivce.agv.task.agvTask.AgvTaskDispatcher;
import me.zhengjie.minbearwcs.serivce.mission.processor.MissionProcessor;
import me.zhengjie.minbearwcs.serivce.mission.processor.MissionProcessorCommonUtil;
import me.zhengjie.minbearwcs.serivce.mission.storageProcessor.locker.Floor3Or4.Storage3Or4FloorLocker;
import me.zhengjie.minbearwcs.utils.IdWorker;

import java.time.LocalDateTime;

@Slf4j
@Component
@RequiredArgsConstructor
public class Inbound3Or4FloorMissionProcessor implements MissionProcessor {

    private final InboundOrderDetailDao inboundOrderDetailDao;
    private final AgvTaskDispatcher getPutTaskDispatcher;
    private final TransactionTemplate transactionTemplate;
    private final WcsMissionDao wcsMissionDao;
    private final WcsResource wcsResource;
    private final IdWorker idWorker;
    private final Storage3Or4FloorLocker storage3Or4FloorLocker;
    private final MissionProcessorCommonUtil commonUtil;
    private final SmallStorageDao smallStorageDao;


    private final Object lock = new Object();


    @Override
    public MissionType getMissionType() {
        return MissionType.INBOUND_3_OR_4_FLOOR;
    }

    @Override
    public void process(WcsMission missionInfo) {
        InboundMissionFor3Or4FloorStatus missionStatus = (InboundMissionFor3Or4FloorStatus) missionInfo.getEnumMissionStatus();

        switch (missionStatus) {
            case WAIT_FOR_STORAGE:
                searchStorage(missionInfo);
                break;
            case SEARCHING_STORAGE:
                break;
            case WAIT_FOR_DISPATCH:
                dispatchAgvTask(missionInfo);
                break;
            case DISPATCHING:
                break;
            case PROCESSING:
                monitorMission(missionInfo);
                break;
            case FINISH:
                finishWcsMission(missionInfo);
                break;
            case CANCEL:
                break;
        }
    }


    public InboundOrderDetail getOrderDetail(Integer detailId) {
        return inboundOrderDetailDao.selectById(detailId);
    }

    private void searchStorage(WcsMission missionInfo) {
        boolean statusChangeSearchStorage = statusChangeSearchStorage(missionInfo.getId());
        if (!statusChangeSearchStorage) {
            return;
        }

        wcsResource.getExecutor().execute(() -> {
            Boolean res = transactionTemplate.execute(status -> {
                try {
                    InboundOrderDetail orderDetail = getOrderDetail(Integer.parseInt(missionInfo.getAssociatedDetailId()));
                    Tuple<String> tuple = storage3Or4FloorLocker.lockStorage(orderDetail.getPalletCode());
                    if (tuple.success) {
                        inboundOrderDetailDao.updateStoragePointById(
                                Integer.parseInt(missionInfo.getAssociatedDetailId()),
                                tuple.value
                        );
                        return true;
                    }
                } catch (Exception e) {
                    log.error("wcs任务{}，3F/4F储位锁定失败", missionInfo.getMissionId(), e);
                    status.setRollbackOnly();
                }
                return false;
            });

            if (Boolean.TRUE.equals(res)){
                wcsMissionDao.updateMissionStatusById(
                        missionInfo.getId()
                        , InboundMissionFor3Or4FloorStatus.WAIT_FOR_DISPATCH.name()
                );
            }else {
                wcsMissionDao.updateMissionStatusById(
                        missionInfo.getId()
                        , InboundMissionFor3Or4FloorStatus.WAIT_FOR_STORAGE.name()
                );
            }

        });


    }

    public boolean statusChangeSearchStorage(Integer missionId) {
        return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
            try {
                if (InboundMissionFor3Or4FloorStatus.WAIT_FOR_STORAGE == wcsMissionDao.selectMissionStatusById(missionId)) {
                    synchronized (lock) {
                        if (InboundMissionFor3Or4FloorStatus.WAIT_FOR_STORAGE == wcsMissionDao.selectMissionStatusById(missionId)) {
                            wcsMissionDao.updateMissionStatusById(missionId, InboundMissionFor3Or4FloorStatus.SEARCHING_STORAGE.name());
                            wcsMissionDao.updateStartTime(missionId, LocalDateTime.now());
                            return true;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("wcs任务状态转换出错", e);
                status.setRollbackOnly();
            }
            return false;
        }));
    }


    public boolean statusChangeDISPATCHING(Integer missionId) {
        return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
            try {
                if (InboundMissionFor3Or4FloorStatus.WAIT_FOR_DISPATCH == wcsMissionDao.selectMissionStatusById(missionId)) {
                    synchronized (lock) {
                        if (InboundMissionFor3Or4FloorStatus.WAIT_FOR_DISPATCH == wcsMissionDao.selectMissionStatusById(missionId)) {
                            wcsMissionDao.updateMissionStatusById(missionId, InboundMissionFor3Or4FloorStatus.DISPATCHING.name());
                            return true;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("wcs任务状态转换出错", e);
                status.setRollbackOnly();
            }
            return false;
        }));
    }


    public void dispatchAgvTask(WcsMission missionInfo) {
        if (!statusChangeDISPATCHING(missionInfo.getId())) return;

        InboundOrderDetail orderDetail = getOrderDetail(Integer.parseInt(missionInfo.getAssociatedDetailId()));


        wcsResource.getExecutor().execute(() -> {
            Boolean executeRes = transactionTemplate.execute(status -> {
                try {
                    String agvTaskId = "Task_Agv_" + idWorker.nextId();
                    AgvTaskSource agvTaskSource = new AgvTaskSource(agvTaskId, AgvMissionType.INBOUND_TYPE, 1, missionInfo.getMissionId(), missionInfo.getMissionType(),
                            InboundMissionFor3Or4FloorStatus.PROCESSING.name(), orderDetail.getPalletCode());
                    agvTaskSource.addAction(new AgvActionSource(smallStorageDao.selectSmallStorageByQrPoint(orderDetail.getStartPoint()), AgvAction.GET))
                            .addAction(new AgvActionSource(smallStorageDao.selectSmallStorageByQrPoint(orderDetail.getStoragePoint()), AgvAction.PUT));


                    if (getPutTaskDispatcher.dispatch(agvTaskSource)) {
                        wcsMissionDao.updateMissionStatusById(missionInfo.getId(), InboundMissionFor3Or4FloorStatus.PROCESSING.name());
                    } else {
                        wcsMissionDao.updateMissionStatusById(missionInfo.getId(), InboundMissionFor3Or4FloorStatus.WAIT_FOR_DISPATCH.name());
                    }
                    return true;
                } catch (Exception e) {
                    log.error("wcs任务：{}，生成agv任务失败", missionInfo.getMissionId(), e);
                    status.setRollbackOnly();
                }
                return false;
            });

            if(Boolean.FALSE.equals(executeRes)){
                wcsMissionDao.updateMissionStatusById(missionInfo.getId(), InboundMissionFor3Or4FloorStatus.WAIT_FOR_DISPATCH.name());
            }

        });
    }


    public void monitorMission(WcsMission missionInfo) {

    }

    public void finishWcsMission(WcsMission missionInfo) {
        transactionTemplate.executeWithoutResult(status -> {
            try {
                missionInfo.setFinishTime(LocalDateTime.now());
                commonUtil.transformMissionHistory(missionInfo);
                inboundOrderDetailDao.updateStatusById(
                        Integer.parseInt(missionInfo.getAssociatedDetailId()),
                        InboundOrderDetailStatus.COMPLETE
                        );
            } catch (Exception e) {
                log.error("任务结束错误", e);
                status.setRollbackOnly();
            }
        });

    }

}
